/**
Zeke Elder - zbe@andrew.cmu.edu
Amal Chemmany - achemman@andrew.cmu.edu
Nishant Kumar - nkumar1@andrew.cmu.edu
15-637
4/2/2012
 **/

package edu.cmu.fithub.actions;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.Session;
import org.mybeans.form.FormBeanException;
import org.mybeans.form.FormBeanFactory;

import edu.cmu.fithub.controller.Action;
import edu.cmu.fithub.db.DBHelper;
import edu.cmu.fithub.db.bean.Group;
import edu.cmu.fithub.db.bean.GroupMembers;
import edu.cmu.fithub.db.bean.User;
import edu.cmu.fithub.formbeans.GroupForm;

public class CreateGroupAction extends Action {

	private FormBeanFactory<GroupForm> formFactory = FormBeanFactory
			.getInstance(GroupForm.class);

	public CreateGroupAction() {
	}

	public String getName() {
		return "createGroup.do";
	}

	public String perform(HttpServletRequest request) {

		List<String> errors = new ArrayList<String>();
		request.setAttribute("errors", errors);
		Group group = new Group();
		try {

			User user = (User) request.getSession().getAttribute("user");

			GroupForm form = formFactory.create(request);
			request.setAttribute("form", form);

			if (!form.isPresent()) {
				return "showHome.do";
			}

			errors.addAll(form.getValidationErrors());
			Session dbSession = DBHelper.getSessionFactory().openSession();
			if (errors.size() > 0) {
				return "showGroupHome.do?groupId=" + group.getGroupId();
			} else {
				group.setGroupName(form.getGroupName());
				group.setGroupDesc(form.getGroupDesc());
				group.setGroupType(form.getGroupType());
				group.setAdminId(user.getUserId());
				dbSession.beginTransaction();
				dbSession.save(group);
				dbSession.getTransaction().commit();
				GroupMembers groupMembers = new GroupMembers();
				groupMembers.setGroup(group);
				groupMembers.setUserId(user.getUserId());
				groupMembers.setUserName(user.getFirstName());
				dbSession.beginTransaction();
				dbSession.save(groupMembers);
				dbSession.getTransaction().commit();
			}

			return "groupsuccess.jsp";

		} catch (FormBeanException e) {
			errors.add(e.toString());
			return "error.jsp";
		}
	}
}
